<?php
namespace app\admin\controller;

use think\Validate;
use think\Controller;
use think\Db;
use think\Crypt;
use Data;


class Index extends Controller
{


    /**
     * 上传
     * @return [type] [description]
     */
    public function uploads(){
        $file = request()->file('file');
        $filePath = request()->post('file_path');
        $type = request()->post('type');
        $path = 'uploads'. DS . $filePath;

        if(isset($file)){
            // 获取表单上传文件 例如上传了001.jpg
            // 移动到框架应用根目录/public/uploads/ 目录下
            $info = $file->move(PATH . DS . $path);
            //       var_dump($info) ;die;

            if($info){
                // 成功上传后 获取上传信息
                $a = $info->getSaveName();
                $imgp = str_replace("\\","/",$a);
                $imgpath = $path . DS . $imgp;

                $filename =  basename($info->getFilename(),'.'.$info->getExtension());
                if($type){
                    //缩略图
                    $thumb = $path . DS . pathinfo($a, PATHINFO_DIRNAME) . DS . $filename . '_thumb_200.' . $info->getExtension();
                    $image = \think\Image::open($imgpath);
                    $image->thumb(400, 400)->save($thumb);
                    $return ['thumb'] = DS . $thumb;
                }

                $image = \think\Image::open($imgpath);
//                $image->thumb(750, 750)->save($imgpath);

                $return ['link'] =  DS . $imgpath;
                exit(json_encode($return));
                //$this->ajaxReturn($imgpath, '成功', 200);
            }else{
                //上传失败获取错误信息
                $msg = $file->getError();
                $this->ajaxReturn('', $msg, 201);
            }
        }

    }




    public function index(){

        //获取权限菜单
        $menu = Db::name('menu')->order('sort','asc')->select();

        //将菜单id作为数组key
        $keys = array_column($menu,'id');
        $menu = array_combine($keys,$menu);
        $menus = Data::channelLevel($menu);
        $this->assign('menus_lists',$menus);

        return $this->fetch();
    }




    /**
     * 检验用户
     * @param $data
     * @return array
     */
    public function checkMember($data){
        $rule = [
            'username|用户名'  => 'require|max:25',
            'password|密码'   => 'number|length:6,16',
            'verify|验证码' => 'require|captcha:login',
        ];
        $validate = new Validate($rule);
        $result   = $validate->check($data);
        if(!$result){
            return ['status'=>false,'message'=>$validate->getError()];
        }

        $map['username'] = $data['username'];
        $map['status'] = 1;
        $this->member = Db::name('admin')->where($map)->find();
        if ( $this->member){
            return ['status' => true, 'data' =>  $this->member];
        }
        return ['status'=>false,'message'=>'用户不存在或被禁用'];
    }

    /**
     * 检查密码是否正确
     * @param $password
     * @return array
     */
    public function checkPass($password){
        if( md5($password.$this->member['token'])!= $this->member['password']){
            return ['status'=>false,'message'=>'密码错误'];
        }
        return ['status'=>true,'message'=>'恭喜！密码正确'];
    }


    /**获取IP
     * @param $message
     */
    public function get_client_ip($type = 0,$adv=false) {
        $type       =  $type ? 1 : 0;
        static $ip  =   NULL;
        if ($ip !== NULL) return $ip[$type];
        if($adv){
            if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
                $arr    =   explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
                $pos    =   array_search('unknown',$arr);
                if(false !== $pos) unset($arr[$pos]);
                $ip     =   trim($arr[0]);
            }elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
                $ip     =   $_SERVER['HTTP_CLIENT_IP'];
            }elseif (isset($_SERVER['REMOTE_ADDR'])) {
                $ip     =   $_SERVER['REMOTE_ADDR'];
            }
        }elseif (isset($_SERVER['REMOTE_ADDR'])) {
            $ip     =   $_SERVER['REMOTE_ADDR'];
        }
        // IP地址合法验证
        $long = sprintf("%u",ip2long($ip));
        $ip   = $long ? array($ip, $long) : array('0.0.0.0', 0);
        return $ip[$type];
    }



    /**
     * 登录页面
     */
    public function login(){
        if(request()->post()){
            $config = config()['login_admin'];
            $data   = request()->post();

            $result = $this->checkMember($data);
            if ($result['status']==false){
                return $result;
            }
            $result = $this->checkPass($data['password']);
            if($result['status']==true){

                session($config['auth_uid'], $this->member['id']);
                session("username", $this->member['username']);

                //登录日志更新
                $this->member['last_login'] = time();
                $this->member['login_ip'] = $this->get_client_ip(0,true);
                Db::name('admin')->where('id',$this->member['id'])->update($this->member);

                //如果记住账号密码-vue.js复选框传的是true和false字符串
                if($data['remember']=='true'){
                    $member['username'] = $data['username'];
                    $member['password'] = $data['password'];
                    $member['remember'] = $data['remember'];
                    $remember = Crypt::encrypt(serialize($member),$config['crypt']);
                    cookie('remember', $remember);//记住我
                }else{
                    cookie('remember', null);
                }

            }
            return $result;
        }
        return $this->fetch();
    }

    /**
     *记住用户名和密码
     */
    public function member(){
        $config = config()['login_admin'];
        $remember = Crypt::decrypt(cookie('remember'),$config['crypt']);
        return unserialize($remember);
    }

    /**
     * 退出
     */
    public function logout(){
        $config = config()['login_admin'];
        session($config['auth_uid'], null);
        session("username", null);
        session(null);
        $this->redirect(url($config['user_auth_gateway']));
    }






}
